// 后端请求
function ajaxCall(method, url, reqData, callback, errorback){
    const token = localStorage.getItem('token');
    $.ajax({
        headers: {
            "token": token
        },
        method: method,
        url: url,
        contentType: 'application/x-www-form-urlencoded',
        data: reqData,
        dataType: 'json',
        async: true,
        success: (respData)=>{
            if(callback){
                callback(respData);
            }else{
                console.log(respData);
            }
        },
        error: (err)=>{
            if(errorback){
                errorback(err);
            }else{
                window.location.href = style.html;
            }
        },
    });
}

function ajaxGet(url, reqData, callback, errorback){
    ajaxCall("GET", url, reqData, callback, errorback);
}

function ajaxPost(url, reqData, callback, errorback){
    ajaxCall("POST", url, reqData, callback, errorback);
}

// 将选择器指向的表单解析成便于验证的 json 对象
function parseForm(formSelector, checkboxMust) {
    let json = {};
    $(formSelector).find('[name]').each((i, e) => {
        let $e = $(e);
        let name = $e.attr("name");
        let val = $e.val();
        let tagName = e.tagName.toLowerCase();
        let type = $e.attr("type");
        let hint = $e.prevAll("span").text();
        if(tagName=="select"){
            json[name] = {
                type: "select",
                required: true,
                val: (val=="0" ? null : val),
                placeholder: `请选择${hint}`
            }
        } else if (type == "radio") {
            if (!json[name]) {
                json[name] = {
                    type: type,
                    required: true,
                    val: null,
                    placeholder: `请选择${hint}`
                };
            }
            if (e.checked) {
                json[name].val = val;
            }
        } else if (type == "checkbox") {
            if (!json[name]) {
                json[name] = {
                    type: type,
                    required: checkboxMust,
                    val: null,
                    placeholder: `请选择${hint}`
                };
            }
            if (e.checked) {
                if(!json[name].val){
                    json[name].val = [];
                }
                json[name].val.push(val);
            }
        } else {
            let required = $e.attr("required") == "required";
            let pattern = $e.attr("pattern");
            let placeholder = $e.attr("placeholder");
            json[name] = {
                type: type,
                required: required,
                pattern: (!pattern || pattern.length==0 ? null : pattern),
                val: val.length==0 ? null : val,
                placeholder: placeholder ? placeholder : `请选择${hint}`
            }
        }
    });
    return json;
}

// 根据选择器解析的 json 对象实现对于表单元素取值的有效性验证
function formSerializeOrFalse(formSelector,checkboxMust,errHandler){
    let json = parseForm(formSelector,checkboxMust);
    let regexChoice = checkboxMust ? /^radio|checkbox|select$/ : /^radio|select$/;
    let regexInput = /^text|password|tel|email|number$/;
    
    let data = {};
   for(const name in json){
       let obj = json[name];
        if(
            (
                // 选择表单元素
                regexChoice.test(obj.type) 
                // 必选，且没选
                && obj.required 
                && !obj.val
            ) || 
            (
                // 输入表单元素
                regexInput.test(obj.type)
                // 必填
                && obj.required 
                && (
                    // 没填
                    !obj.val || 
                    // 填错了 
                    (obj.pattern && !new RegExp(obj.pattern).test(obj.val))
                )
            )
        ){
            if(errHandler){
                errHandler(obj.placeholder);
            }else{
                alert(obj.placeholder);
            }
            return false;
        }else{
            data[name] = obj.val;
        }
    }
    return data;
}

// 展示弹窗
// 弹窗关闭按钮：事件预绑定
$(document).on('click','.alert-btn-close',()=>{
    $(event.target).parents('.alert-window').remove();
});

function alert(type,content){
    const title = type=="info" ? "信息" : type=="warn" ? "警告" : "错误";
    const $box = $(`
        <div class="alert-window">
            <div class="alert-box ${type}-box">
                <div class="alert-btn-close btn">X</div>
                <div class="alert-title">${title}提示</div>
                <div class="alert-content">${content}</div>
            </div>
        </div>
    `);
    $("body").append($box);
}

function info(content){
    alert("info",content);
}
function warn(content){
    alert("warn",content);
}
function error(content){
    alert("error",content);
}

// Json 和 formFormatString 转换
function jsonToFormString(json){
    let array = [];
    for(const key in json){
        array.push(`${key}=${json[key]}`);
    }
    return array.join("&");
}

function formStringToJson(formString){
    let json = {};
    const regexInt = /^\d+$/;
    const regexFloat = /^\d*\.\\d+|\d+\.\\d*$/;
    const regexBool = /^true|false$/;
    formString.split("&").forEach((kv)=>{
        const arr = kv.split("=");
        const val = arr[1];
        json[arr[0]] = regexInt.test(val) ? parseInt(val) :
                        regexFloat.test(val) ? parseFloat(val) :
                        regexBool.test(val) ? val=="true" : val;
    });
    return json;
}

// 页面跳转（可与携带少量的数据）
function redirect(url, json, method){
    if(json){
        const formStr = jsonToFormString(json);
        if(method.toLowerCase()=="get"){
            window.location.href = `${url}?${formStr}`;
        }else{
            window.location.href = `${url}?method=post`;
            localStorage.setItem("LOAD_INIT_DATA",formStr);
        }
    }else{
        window.location.href = url;
    }
}

// 页面加载时解析 url 中挂载的数据为 json
function loadParse(){
    const url = window.location.href;
    const regexKV = /^\w+=.*?(&\w+=.*?)*$/;
    let json = {};
    let arr = url.split('?');
    if(arr.length==2){
        if(regexKV.test(arr[1])){
            json = formStringToJson(arr[1]);
        }
    }
    if(json.method && json.method.toLowerCase()=='post'){
        data = localStorage.getItem("LOAD_INIT_DATA");
        if(data){
            localStorage.removeItem("LOAD_INIT_DATA");
            if(regexKV.test(data)){
                json = formStringToJson(data);
            }
        }
    }
    return json;
}
// 发送POST请求
fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: data.toString()
})
.then(response => response.json())
.then(data => {
    console.log('Login response:', data);
    document.getElementById('message').textContent = data.data;
})
.catch(error => {
    console.error('Error:', error);
});
$(document).ready(function(){
    let json = loadParse();
    console.log(json);
})
$.ajax({
    url: 'http://localhost:8090/user/login',
    method: 'POST',
    data: data.toString(), // 转换为字符串格式
    contentType: 'application/x-www-form-urlencoded', // 设置Content-Type
    success: function(response) {
        console.log('Login response:', response);
        // 在这里可以处理登录成功或失败的情况
    },
    error: function(error) {
        console.error('Error:', error);
    }
});